package com.xpgk.mvc.statistic.customerInfo;


import java.math.BigDecimal;
import java.security.Key;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xpgk.constant.ConstantSplitPage;
import com.xpgk.dto.SplitPage;
import com.xpgk.mvc.RSACoder;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.binShopService.CustomerService;
import com.xpgk.mvc.binShopService.ServicePartSize;
import com.xpgk.mvc.binShopService.ServiceShaping;
import com.xpgk.mvc.bloseWeight.DelWeiTarget;
import com.xpgk.mvc.bloseWeight.DelWeiTargetSum;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.dept.Department;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productOrgExperience.ProductOrgExperience;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.daySales.DaySalesStatisticSQL;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolDateTime;

public class CustomerInfoStatisticController extends BaseController {
	
	/**
	 * 是否到处 1为是0为否
	 */
	public int xls;
	
	private CustomerInfoStatisticService  customerInfoStatisticService;
	
	
	public void index() throws Exception {
		/*String sql = "select * from sb_customer";
   	 List<Customer> cusList = Customer.dao.find(sql);
   	 if(cusList!=null && cusList.size()>0){
   		 for(Customer cus:cusList){
   			 String testString = cus.getStr(Customer.column_phone);
   			
	         byte[] decryptString = RSACoder.decryptByPrivateKey(encryptString, privateKey);
	         
   		 }*/
		/* String sql = "select * from sb_customer";
    	 List<Customer> cusList = Customer.dao.find(sql);
    	 if(cusList!=null && cusList.size()>0){
    		 for(Customer cus:cusList){
    			 String testString = cus.getStr(Customer.column_phone);
    			  //初始化密钥
    	         Map<String, Key> map = RSACoder.initKey();
    	         //获取公钥
    	         String publicKey = RSACoder.getPublicKey(map);
    	         //获取私钥
    	         String privateKey = RSACoder.getPrivateKey(map);
    	         *//**
    	          * 公钥加密，私钥解密
    	          *//*
    	         byte[] encryptString = RSACoder.encryptByPublicKey(testString, publicKey);
    	         byte[] decryptString = RSACoder.decryptByPrivateKey(encryptString, privateKey);
    	         //输出结果
    	         System.out.println(new String(decryptString));
    	        

    	        *//**
    	          * 私钥加密，公钥解密
    	          *//*
    	         encryptString = RSACoder.encryptByPrivateKey(testString.getBytes("UTF-8"), privateKey);
    	         decryptString = RSACoder.decryptByPublicKey(encryptString, publicKey);
    	         //输出结果
    	         System.out.println(new String(decryptString));
    	         cus.set(Customer.column_phone, new String(encryptString));
    	         cus.update();

    	         *//**
    	          * 验签
    	          *//*
    	         String signedData = RSACoder.sign(testString.getBytes(), privateKey);
    	         boolean is = RSACoder.verify(testString.getBytes(), publicKey, signedData);
    	         System.out.println(is);

    	         *//**
    	          * 用无Base64的密钥加解密
    	          *//*
    	         encryptString = RSACoder.encryptByPublicKey(testString, RSACoder.getPublicKeyNoBase64(map));
    	         decryptString = RSACoder.decryptByPrivateKey(encryptString, RSACoder.getPrivateKeyNoBase64(map));
    	         System.out.println(new String(decryptString));

    		 }
    	 
        // String testString = "{\"data\":\"测试\"}";

       
     }

		*/
		
		
		
		setAttr("curOrgan", Organization.dao.findById(getCUserOrganIds()));
	//	setAttr("startTime", ToolDateTime.getMonthOneDay(new Date()));
		render("customerInfoStatistic.html");
	}
	
	/**
	 * 顾客列表
	 */
	public void view(){
		String organMangerIds = (String) splitPage.getQueryParam().get("organMangerIds");
		if(null != organMangerIds && !organMangerIds.equals("-1")){
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", Organization.column_mangerIds);
			String sql = getSqlByBeetl(Organization.sqlId_column, param);
			List<Organization> organs = Organization.dao.find(sql, organMangerIds);
			if(organs.size() > 0){
				List<String> bhs = new ArrayList<String>();
				int bhLength = 0;
				for(Organization organ : organs){
					String bh = organ.getStr(Organization.column_bh);
					bhLength = bh.length();
					bhs.add(bh);
				}
				splitPage.getQueryParam().remove("selOrganIds");
				splitPage.getQueryParam().put("bhs", bhs);
				splitPage.getQueryParam().put("bhLength", String.valueOf(bhLength));
			}
		}
		SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd");
		String now = sdt.format(new Date());
		splitPage.getQueryParam().put("now",now );
		String json = paging(splitPage, CustomerInfoStatisitSQL.sqlId_splitPageSelect, CustomerInfoStatisitSQL.sqlId_splitPageFrom);
		
//		String[] header={"id","试题名称","创建时间","更新时间","操作者","是否有效"};
//	    String[] columns={"id","name","userName","hybh","sex","age"};
//	    render(new XlsRender((List<Record>) splitPage.getList(), header, columns, "aaaaa"));
////		Render poirender = PoiRender.me(splitPage.getList()).fileName("carInfo.xls").headers(header).sheetName("试题表").columns(columns);
////		render(poirender);
		renderJson(json);
	}
	public   void  excel() 
	{
		SplitPage  splitPage=new SplitPage();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("startTime", getPara("_query.startTime"));
		param.put("endTime", getPara("_query.endTime"));
		param.put("selOrganIds", getPara("_query.selOrganIds"));
		String organMangerIds = getPara("_query.organMangerIds");
		if(null != organMangerIds && !organMangerIds.equals("-1")){
			Map<String, Object> param1 = new HashMap<String, Object>();
			param1.put("column", Organization.column_mangerIds);
			String sql = getSqlByBeetl(Organization.sqlId_column, param1);
			List<Organization> organs = Organization.dao.find(sql, organMangerIds);
			if(organs.size() > 0){
				List<String> bhs = new ArrayList<String>();
				int bhLength = 0;
				for(Organization organ : organs){
					String bh = organ.getStr(Organization.column_bh);
					bhLength = bh.length();
					bhs.add(bh);
				}
				param.remove("selOrganIds");
				param.put("bhs", bhs);
				param.put("bhLength", String.valueOf(bhLength));
			}
		}
		param.put("selDempmentIds", getPara("_query.selDempmentIds").equals("-1")?"":getPara("_query.selDempmentIds"));
		param.put("customerManger", getPara("_query.customerManger").equals("-1")?"":getPara("_query.customerManger"));
		param.put("hybh", getPara("_query.hybh"));
		param.put("customerName", getPara("_query.customerName"));
		param.put("customerPhone", getPara("_query.customerPhone"));
		param.put("customerSex", getPara("_query.customerSex").equals("-1")?"":getPara("_query.customerSex"));
		param.put("jdfs", getPara("_query.jdfs").equals("-1")?"":getPara("_query.jdfs"));
		param.put("lc", getPara("_query.lc").equals("-1")?"":getPara("_query.lc"));
		param.put("treatment", getPara("_query.treatment").equals("-1")?"":getPara("_query.treatment"));
		param.put("days", getPara("_query.days"));
		param.put("state", getPara("_query.state").equals("-1")?"":getPara("_query.state"));
		splitPage.setPageSize(ConstantSplitPage.default_maxSize);
		splitPage.setQueryParam(param);
		String json = paging(splitPage, CustomerInfoStatisitSQL.sqlId_splitPageSelect, CustomerInfoStatisitSQL.sqlId_splitPageFrom);
		List<Record>  list=(List<Record>)splitPage.getList();
		for(int i=0;i<list.size();i++)
		{
			if(list.get(i).get("state").equals("1"))
			{
				list.get(i).set("state", "服务中");
			}else
			{
				list.get(i).set("state", "停止服务");
			}
		}
		//搜索条件
		Organization organ=Organization.dao.findById(getPara("_query.selOrganIds"));//门店
		User  scfzr=User.dao.findById(getPara("_query.organMangerIds"));//市场负责人
		Department  mdxz=Department.dao.findById(getPara("_query.selDempmentIds"));//门店小组
		User  gkfzr=User.dao.findById(getPara("_query.customerManger"));//顾客负责人
		Code  jdfc=Code.dao.findById(getPara("_query.jdfs"));//进店方式
		Product  lc=Product.dao.findById(getPara("_query.lc"));//疗程
		String  scfzrstr=scfzr==null?"":(",市场负责人："+scfzr.getStr(User.column_name));//市场负责人name
		String  mdxzstr=mdxz==null?"":(",门店小组："+mdxz.getStr(Department.column_name));//门店小组name
		String  gkfzrstr=gkfzr==null?"":(",顾客负责人："+gkfzr.getStr(User.column_name));//顾客负责人name
		String  cusbhstr=getPara("_query.hybh").equals("")?"":(",顾客编号："+getPara("_query.hybh"));//顾客编号
		String  cusnamestr=getPara("_query.customerName").equals("")?"":(",顾客姓名："+getPara("_query.customerName"));//顾客姓名
		String  cusphonestr=getPara("_query.customerPhone").equals("")?"":(",顾客手机："+getPara("_query.customerPhone"));//顾客手机
		String  cussexstr=getPara("_query.customerSex").equals("-1")?"":(",顾客性别："+getPara("_query.customerSex"));//顾客性别
		String  jdfcstr=jdfc==null?"":(",进店方式："+jdfc.getStr(Code.column_name));//进店方式name
		String  lcstr=lc==null?"":(",疗程："+lc.getStr(Product.column_name));//疗程name
		String  treatmentstr=getPara("_query.treatment").equals("-1")?"":(",疗程数："+getPara("_query.treatment"));//疗程数
		String  daysstr=getPara("_query.days").equals("")?"":(",未到店天数："+getPara("_query.days"));//未到店天数
		String  statestr=getPara("_query.state").equals("-1")?"":(",服务状态："+getPara("_query.state"));//服务状态
		//搜索条件字符串
		String  search="进店时间："+getPara("_query.startTime")+"~"+getPara("_query.endTime")+",门店："+organ.getStr(Organization.column_name)+
				scfzrstr+mdxzstr+gkfzrstr+cusbhstr+cusnamestr+cusphonestr+cussexstr+jdfcstr+lcstr+treatmentstr+daysstr+statestr+
				",导出人员："+getCUser().getStr(User.column_name);
		render(new CustomerInfoStatisticXLS(list,search,"顾客档案"));
	}
	/**
	 * 顾客详情
	 */
	public void lookCustomerInfo(){
		Customer customer = Customer.dao.findById(ids);
		setAttr("customer", customer);
		setAttr("customerDetail", customer.getCustomerDetail());
		setAttr("customerAgreement", customer.getCustomerAgreement());
		render("customerInfo.html");
	}
	
	/**
	 * 跳转至消费记录
	 */
	public void toLookCustomerExpense(){
		setAttr("customerIds", getPara("customerIds"));
		setAttr("startTime", ToolDateTime.getMonthOneDay(new Date()));
		render("/customer/customerExpense.html");
	}
	
	/**
	 * 消费记录列表
	 */
	public void lookCustomerExpense(){
		String json = paging(splitPage, CustomerInfoStatisitSQL.sqlId_lookCustomerExpenseSelect, CustomerInfoStatisitSQL.sqlId_lookCustomerExpenseFrom);
		renderJson(json);
	}
	
	/**
	 * 跳转至消费详情
	 */
	public void toLookCustomerExpenseDetail(){
		setAttr("orderIds", getPara("orderIds"));
		render("/customer/customerExpenseDetail.html");
	}
	
	/**
	 * 消费详情列表
	 */
	public void lookCustomerExpenseDetail(){
		String json = paging(splitPage, CustomerInfoStatisitSQL.sqlId_lookCustomerExpenseDetailSelect, CustomerInfoStatisitSQL.sqlId_lookCustomerExpenseDetailFrom);
		renderJson(json);
	}
	
	/**
	 * 跳转至服务记录
	 */
	public void toLookCustomerService(){
		setAttr("customerIds", getPara("customerIds"));
		setAttr("startTime", ToolDateTime.getMonthOneDay(new Date()));
	
		
		String sqlbb = "SELECT * FROM sb_product_orgexperience where organIds =? and bbExperience IS NOT NULL and dataStatus = '1'";
		String sqlkb = "SELECT * FROM sb_product_orgexperience where organIds =? and kbExperience IS NOT NULL and dataStatus = '1'";
		String sqlfr = "SELECT * FROM sb_product_orgexperience where organIds =? and frExperience IS NOT NULL and dataStatus = '1'";
		ProductOrgExperience bb = ProductOrgExperience.dao.findFirst(sqlbb,getCUserOrganIds());
		int n = 4;
		if(bb!=null){
			n++;
			setAttr("bbExp", "1");
		}else{
			setAttr("bbExp", "0");
		}
		ProductOrgExperience kb = ProductOrgExperience.dao.findFirst(sqlkb,getCUserOrganIds());
		if(kb!=null){
			n++;
			setAttr("kbExp", "1");
		}else{
			setAttr("kbExp", "0");
		}
		ProductOrgExperience fr = ProductOrgExperience.dao.findFirst(sqlfr,getCUserOrganIds());
		if(fr!=null){
			n = n+2;
			setAttr("Exp", "1");
		}else{
			setAttr("Exp", "0");
		}
		setAttr("partnum",n);
		render("/customer/customerService.html");
	}
	
	/**
	 * 服务记录列表
	 */
	public void lookCustomerService(){
		String json = paging(splitPage, CustomerInfoStatisitSQL.sqlId_lookCustomerServiceSelect, CustomerInfoStatisitSQL.sqlId_lookCustomerServiceFrom);
		renderJson(json);
	}
	
	/**
	 * 跳转至服务记录详情
	 */
	public void toLookCustomerServiceDetail(){
		setAttr("serviceIds", getPara("serviceIds"));
		
		render("/customer/customerServiceDetail.html");
	}
	
	/**
	 * 服务记录详情列表
	 */
	public void lookCustomerServiceDetail(){

		String json = paging(splitPage, CustomerInfoStatisitSQL.sqlId_lookCustomerServiceDetailSelect, CustomerInfoStatisitSQL.sqlId_lookCustomerServiceDetailFrom);
		renderJson(json);
	}
	
	/*
	 * 删除服务
	 */
	@Before(Tx.class)
	public void deleteService() throws ParseException{
		String serviceIds = getPara("ids");
		/*String ybjyusage = getPara("ybjyusage");
		String bbjyusage = getPara("bbjyusage");
 		String kbjyusage = getPara("kbjyusage");
		String gbjyusage = getPara("gbjyusage");
		String zfrjyusage = getPara("zfrjyusage");
		String yfrjyusage = getPara("yfrjyusage");
		String dtjyusage = getPara("dtjyusage");
		String xtjyusage = getPara("xtjyusage");
		String gbgusage = getPara("gbgusage");
		String kbgusage = getPara("kbgusage");
		String bbgusage = getPara("bbgusage");
		String ybgusage = getPara("ybgusage");
		String zfrgusage = getPara("zfrgusage");
		String yfrgusage = getPara("yfrgusage");
		String dtgusage = getPara("dtgusage");
		String xtgusage = getPara("xtgusage");*/
		boolean result = customerInfoStatisticService.deleteService(serviceIds,getCUserIds(),getCUserOrganIds());
		//boolean result = customerInfoStatisticService.deleteService(ids,getCUserIds(),getCUserOrganIds(),ybgusage,ybjyusage,dtjyusage,dtgusage,xtgusage,xtjyusage,gbgusage,gbjyusage,zfrgusage,zfrjyusage,yfrgusage,yfrjyusage,bbgusage,bbjyusage,kbgusage,kbjyusage);
		
		/*CustomerService customerService = CustomerService.dao.findById(ids);
		if(customerService!=null){
			customerService.set(CustomerService.column_dataStatus, "0");
			result = customerService.update();
		}*/
		
		
		renderJson(result);
	}

	
	/**
	 * 部位尺寸
	 */
	public void toLookCustomerPartSize(){
		
		String date = getPara("date");
		String customerIds = getPara("customerIds");
		String _sql = getSqlMy(ServicePartSize.sqlId_selLastSize);
		List<Record> sizes = Db.find(_sql, customerIds, date);
		
		String sizes_json = JsonKit.toJson(sizes);
		setAttr("sizes", sizes_json);
		render("/customer/customerPartSize.html");
	}
	
	/**
	 * 跳转至产品购买查询
	 */
	public void toLookCustomerProductSales(){
		String sql = getSqlMy(DaySalesStatisticSQL.sqlId_product);
		setAttr("products", Db.find(sql, Code.lc_ids, Code.proYtLX_ids));
		setAttr("startTime", ToolDateTime.getMonthOneDay(new Date()));
		setAttr("customerIds", getPara("customerIds"));
		render("/customer/customerProductSales.html");
	}
	
	/**
	 * 产品购买列表
	 */
	public void lookCustomerProductSales(){
		String customerIds = getPara("customerIds", "-1");
		String startTime = getPara("startTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		String endTime = getPara("endTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		List<Record> result = new ArrayList<>();
		if(!customerIds.equals("-1")){
			String sql_customerSales = getSqlMy(CustomerInfoStatisitSQL.sqlId_lookCustomerProductSales);
			List<Record> cus_sales = Db.find(sql_customerSales, customerIds, startTime, endTime);
			if(cus_sales.size() > 0){
				for(Record sales : cus_sales){
					Record r = new Record();
					Double sum = 0.0;
					//单疗程
					if(sales.getStr("xflb").equals("xflbgm") && sales.getStr("type").equals(Code.lc_ids) && sales.getStr("units").equals(Code.dlc_units)){
						r.set("singleLc_unitPrice", sales.getFloat("unitPrice"));
						r.set("singleLc_totalPrice", sales.getDouble("totalPrice"));
					}
					
					//标准疗程
					if(sales.getStr("xflb").equals("xflbgm") && sales.getStr("type").equals(Code.lc_ids) && sales.getStr("units").equals(Code.bzlc_units)){
						r.set("normLc_lcNum", sales.getBigDecimal("num"));
						r.set("normLc_unitPrice", sales.getFloat("unitPrice"));
						r.set("normLc_totalPrice", sales.getDouble("totalPrice"));
					}
					
					//转疗程
					if(sales.getStr("xflb").equals("xflbzx") && sales.getStr("type").equals(Code.lc_ids)){
						r.set("upLc_lcNum", sales.getBigDecimal("num"));
						r.set("upLc_totalPrice", sales.getFloat("receivable"));
					}
					
					//其他产品
					if(sales.getStr("xflb").equals("xflbgm") && !sales.getStr("type").equals(Code.lc_ids)){
						r.set(sales.getStr("bh") + "_num", sales.getBigDecimal("num"));
						r.set(sales.getStr("bh") + "_price", sales.getDouble("totalPrice"));
						sum += sales.getDouble("totalPrice");
					}
					r.set("producttotalprice", sum);
					r.set("date", sales.getStr("date"));
					result.add(r);
				}
			}
		}
		renderJson(result);
		
	}
	
	/**
	 * 跳转至塑形尺寸统计查询
	 */
	public void toLookCustomerPartSizeStatistic(){
		setAttr("parts", Code.cacheGetChild(Code.fwbw_ids));
		setAttr("startTime", ToolDateTime.getMonthOneDay(new Date()));
		setAttr("customerIds", getPara("customerIds"));
	
		render("/customer/customerPartSizeStatistic.html");
	}
	
	/**
	 * 塑形尺寸统计列表
	 */
	public void lookCustomerPartSizeStatistic(){
		String customerIds = getPara("customerIds", "-1");
		String startTime = getPara("startTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		String endTime = getPara("endTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		List<Record> result = new ArrayList<>();
		
		String sql_dates = getSqlMy(CustomerInfoStatisitSQL.sqlId_customerPartSizeRecord2);
		List<Record> cus_dates = Db.find(sql_dates, startTime, endTime, customerIds);
		
		
			
	
		/*if(!customerIds.equals("-1")){
			String sql_dates = getSqlMy(CustomerInfoStatisitSQL.sqlId_customerPartSizeRecord);
			List<Record> cus_dates = Db.find(sql_dates, startTime, endTime, customerIds);
			if(cus_dates.size() > 0){
				for(Record r : cus_dates){
					String sql = getSqlMy(CustomerInfoStatisitSQL.sqlId_customerPartSize);
					List<Record> partSizes = Db.find(sql, customerIds, r.getStr("date"));
					if(partSizes.size() > 0){
						for(Record size : partSizes){
							r.set(Code.cacheGet(size.getStr("partIds")).getStr(Code.column_code), size.getFloat("size"));
						}
					}
					result.add(r);
				}
			}
		}*/
		renderJson(cus_dates);
	}
	/**
	 * 跳转至生活日常
	 */
	public  void  toLookCustomerLivingHabitStatistic()
	{
		setAttr("customerIds", getPara("customerIds"));
		setAttr("startTime", ToolDateTime.getMonthOneDay(new Date()));
		render("/customer/customerLivingHabit.html");
	}
	/**生活日常列表
	 * @throws ParseException 
	 * 
	 */
	public  void  LookCustomerLivingHabitStatistic() throws ParseException
	{
		String customerIds=getPara("customerIds");
		String startTime=getPara("startTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		String endTime=getPara("endTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
	    
	    String  sql = getSqlMy(CustomerInfoStatisitSQL.sqlId_customerLivingHabit);
	    List<Customer>  cList= Customer.dao.find(sql,customerIds,startTime,endTime);
	    renderJson(cList);
	}
	
	
	/**
	 * 跳转至减重目标完成情况
	 */
	public void toCustomerTargetStatistic(){
		setAttr("customerIds", getPara("customerIds"));
		render("/customer/customerTargetStatistic.html");
	}
	
	/**
	 * 减重目标完成情况列表
	 */
	public void customerTargetStatistic(){
		String customerIds = getPara("customerIds", "-1");
		/*String sql = "SELECT * from sb_customer_detail where customerIds = ? and dataStatus in (1,2)";
		CustomerDetail customerDetail = CustomerDetail.dao.findFirst(sql,customerIds);*/
		List<Record> result = new ArrayList<>();
		if(!customerIds.equals("-1")){
			List<DelWeiTargetSum> targetSums =  DelWeiTargetSum.dao.getTargetsByCustomer(customerIds);
			if(targetSums.size() > 0){
				int planNum_total = 0;
				float target_total = 0;
				int real_planNum_total = 0;
				float real_target_total = 0;
				for(int i = 0; i < targetSums.size(); i++){
					List<DelWeiTarget> targets = DelWeiTarget.dao.findTargetBySum(targetSums.get(i).getPKValue());
					if(targets.size() > 0){
						int planNum_sum = 0;
						float target_sum = 0;
						int real_planNum_sum = 0;
						float real_target_sum = 0;
						for(DelWeiTarget target : targets){
							Record r = new Record();
							r.set("jd", "第 " + (i+1) + " 月");
							r.set("pq", target.getStr(DelWeiTarget.column_schedule));
							r.set("startTime", target.getDate(DelWeiTarget.column_startTime));
							r.set("endTime", target.getDate(DelWeiTarget.column_endTime));
							r.set("planNum", target.getInt(DelWeiTarget.column_planToStoreNum));
							if(target.getInt(DelWeiTarget.column_planToStoreNum)!=null){
								planNum_sum += target.getInt(DelWeiTarget.column_planToStoreNum);
							}
							
							r.set("target", target.getFloat(DelWeiTarget.column_delWeiTarget));
							if(target.getFloat(DelWeiTarget.column_delWeiTarget)!=null){
								target_sum += target.getFloat(DelWeiTarget.column_delWeiTarget);
							}
							
							
							String sql_service = getSqlMy(CustomerInfoStatisitSQL.sqlId_customerServices);
							List<Record> services = Db.find(sql_service, customerIds, target.getDate(DelWeiTarget.column_startTime), target.getDate(DelWeiTarget.column_endTime));
							r.set("realPlanNum", services.size());
							real_planNum_sum += services.size();
							if(services.size() == 0){
								r.set("realTarget", 0);
								real_target_sum += 0;
							}else if(services.size() > 0){
								float weight = 0;
								if(services.size()==1){
									
									weight =services.get(0).getFloat("lastWeight")-services.get(0).getFloat("weight");
								}else{
									float lsst = services.get(services.size() - 1).getFloat("weight");
									weight = services.get(0).getFloat("weight") - services.get(services.size() - 1).getFloat("weight");
								}
								
								r.set("realTarget", weight);
								real_target_sum += weight;
							}
							result.add(r);
						}
						
						//汇总
						Record r_sum = new Record();
						r_sum.set("jd", "第 " + (i+1) + " 月");
						r_sum.set("pq", "汇总");
						r_sum.set("startTime", targetSums.get(i).getDate(DelWeiTargetSum.column_startTime));
						r_sum.set("endTime", targetSums.get(i).getDate(DelWeiTargetSum.column_endTime));
						r_sum.set("planNum", planNum_sum);
						r_sum.set("target", target_sum);
						r_sum.set("realPlanNum", real_planNum_sum);
						r_sum.set("realTarget", real_target_sum);
						
						result.add(r_sum);
						
						//合计
						planNum_total += planNum_sum;
						target_total += target_sum;
						real_planNum_total += real_planNum_sum;
						real_target_total += real_target_sum;
					}
					
				}
				
				//合计
				Record total = new Record();
				total.set("jd", "合计");
				total.set("startTime", targetSums.get(0).getDate(DelWeiTargetSum.column_startTime));
				total.set("endTime", targetSums.get(targetSums.size() - 1).getDate(DelWeiTargetSum.column_endTime));
				total.set("planNum", planNum_total);
				total.set("target", target_total);
				total.set("realPlanNum", real_planNum_total);
				total.set("realTarget", real_target_total);
				result.add(total);
			}
		}
		renderJson(result);
		
	}
	
	/**
	 * 跳转至体重趋势查询
	 */
	public void toCustomerWeightStatistic(){
		String customerIds = getPara("customerIds", "-1");
		String startTime = getPara("startTime", ToolDateTime.getMonthOneDay(new Date()));
		String endTime = getPara("endTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		
		String sql_service = getSqlMy(CustomerInfoStatisitSQL.sqlId_customerServices);
		List<Record> services = Db.find(sql_service, customerIds, startTime, endTime);
		setAttr("services", services);
		
		setAttr("customer", Customer.dao.findById(customerIds));
		setAttr("customerIds", customerIds);
		setAttr("startTime", startTime);
		setAttr("endTime", endTime);
		render("/customer/customerWeightStatistic.html");
	}
	
	
	/**
	 * 跳转至满意体重
	 */
	@Before(Tx.class)
	public void showSatisfy(){
		setAttr("customerIds", getPara("customerIds"));
		render("/customer/customerSatisfy.html");
	}
	public void updateSatisfy(){
		String customerIds = getPara("cusIds");
		String msg = "修改成功";
		String sql = "SELECT * FROM sb_customer_detail WHERE customerIds = ? and dataStatus in ('1','2')";
		if(customerIds!=null && !customerIds.equals("")){
			CustomerDetail cdet = CustomerDetail.dao.findFirst(sql,customerIds);
			if(cdet!=null && cdet.getStr(CustomerDetail.column_customerType)!=null && !cdet.getStr(CustomerDetail.column_customerType).equals("")){
				String cusType = cdet.getStr(CustomerDetail.column_customerType);
				if(cusType.equals("2")){
					msg = "该顾客已经是巩固顾客，不能进行此操作";
				}else if(cusType.equals("1")){
					msg = "该顾客是塑形顾客，不能进行此操作";
				}else if(cusType.equals("0")){
					String sqlSer = "SELECT * FROM sb_customer_service WHERE customerID =? and DATE_FORMAT(startTime, '%Y-%m-%d') = ? and dataStatus in ('1','2') ";
					CustomerService cs = CustomerService.dao.findFirst(sqlSer,customerIds,ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
					if(cs!=null){
						//如果服务不为空  把服务当天店内达标人数加1
						cdet.set(CustomerDetail.column_customerType, "2");
						if(!cdet.update()){
							msg = "顾客详情更新失败";
						}
						String bz ="";
						if(cs.getStr(CustomerService.column_bz)!=null){
							bz = cs.getStr(CustomerService.column_bz);
						}
						 
						cs.set(CustomerService.column_isGg, "1")
						.set(CustomerService.column_bz, bz+"手动设置为满意体重");
						if(!cs.update()){
							msg = "服务记录更新失败";
						}
						DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(getCUserOrganIds(),new Date());
						if(dnt!=null){
							dnt.set(DailyNursingTotal.column_dbrs, dnt.getInt(DailyNursingTotal.column_dbrs)+1);
							if(!dnt.update()){
								msg = "日综合表更新失败";
							}
						}
					}else{
						msg ="当天该顾客没有服务记录，不能进行此操作";
					}
					
					
				}
			}else{
				msg = "顾客类型为空";
			}
		}else{
			msg = "顾客信息查找失败";
		}
		renderText(msg);
	}
	
	
	
	/**
	 * 跳转至产品购销存查询
	 */
	public void toCustomerProductGXC(){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", Product.column_useIds);
		String sql = getSqlByBeetl(Product.sqlId_column, param);
		List<Product> products = Product.dao.find(sql, Code.cpytFw_ids);
		List<Code> parts = Code.cacheGetChild(Code.fwbw_ids);
		setAttr("products", products);
		setAttr("parts", parts);
		setAttr("startTime", ToolDateTime.getMonthOneDay(new Date()));
		setAttr("customerIds", getPara("customerIds"));
		
		
		String sqlbb = "SELECT * FROM sb_product_orgexperience where organIds =? and bbExperience IS NOT NULL and dataStatus = '1'";
		String sqlkb = "SELECT * FROM sb_product_orgexperience where organIds =? and kbExperience IS NOT NULL and dataStatus = '1'";
		String sqlfr = "SELECT * FROM sb_product_orgexperience where organIds =? and frExperience IS NOT NULL and dataStatus = '1'";
		ProductOrgExperience bb = ProductOrgExperience.dao.findFirst(sqlbb,getCUserOrganIds());
		int n = 4;
		if(bb!=null){
			n++;
			setAttr("bbExp", "1");
		}else{
			setAttr("bbExp", "0");
		}
		ProductOrgExperience kb = ProductOrgExperience.dao.findFirst(sqlkb,getCUserOrganIds());
		if(kb!=null){
			n++;
			setAttr("kbExp", "1");
		}else{
			setAttr("kbExp", "0");
		}
		ProductOrgExperience fr = ProductOrgExperience.dao.findFirst(sqlfr,getCUserOrganIds());
		if(fr!=null){
			n = n+2;
			setAttr("Exp", "1");
		}else{
			setAttr("Exp", "0");
		}
		setAttr("partnum",n);
		render("/customer/customerProductGXC.html");
	}
	
	/**
	 * 产品购销存列表
	 * @throws ParseException 
	 */
	public void customerProductGXC() throws ParseException{
		String customerIds = getPara("customerIds", "-1");
		String startTime = getPara("startTime", ToolDateTime.getMonthOneDay(new Date()));
		String endTime = getPara("endTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		List<Record> result = new ArrayList<>();
		if(!customerIds.equals("-1")){
			List<String> days = ToolDateTime.getDaysByStartAndEnd(startTime, endTime);
			int i= 0;
			if(days.size() > 0){
				for(String day : days){
					i++;
					Record r = new Record();
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("column", Product.column_useIds);
					String sql = getSqlByBeetl(Product.sqlId_column, param);
					Product jyproduct = Product.dao.findById("95e2ae17462e4d0eb1dc84bc63bc478a");
					Product gproduct = Product.dao.findById("daaba791f4104ae98504a1bc421e0d8d");
					//List<Product> jyproducts = Product.dao.find(sql, Code.cpytFw_ids);//产品
				//	List<Code> parts = Code.cacheGetChild(Code.fwbw_ids);//服务部位
					
					//产品使用
					
					String sql_service = getSqlMy(CustomerInfoStatisitSQL.sqlId_customerIsService);
					Record service = Db.findFirst(sql_service, customerIds, day);
					String sql_shaping = "SELECT * from sb_customer_service_shaping where serviceIds = ? and dataStatus in ('1','2')";
					
					if(null != service){
						ServiceShaping serviceShaping = ServiceShaping.dao.findFirst(sql_shaping,service.getStr(CustomerService.column_ids));
						
						//Double sy_sum =0.0;
						float ybjy = 0f;
						float gbjy = 0f;
						float dtjy = 0f;
						float xtjy = 0f;
						float ybg = 0f;
						float gbg = 0f;
						float tdg = 0f;
						float xyg = 0f;
						
						float bbjy = 0f;
						float kbjy = 0f;
						float zfrjy = 0f;
						float yfrjy = 0f;
						float bbg = 0f;
						float kbg = 0f;
						float zfrg = 0f;
						float yfrg = 0f;
						float sumjy = 0f;
						float sumg = 0f;
						
						String sqlbb = "SELECT * FROM sb_product_orgexperience where organIds =? and bbExperience IS NOT NULL and dataStatus = '1'";
						String sqlkb = "SELECT * FROM sb_product_orgexperience where organIds =? and kbExperience IS NOT NULL and dataStatus = '1'";
						String sqlfr = "SELECT * FROM sb_product_orgexperience where organIds =? and frExperience IS NOT NULL and dataStatus = '1'";
						ProductOrgExperience bb = ProductOrgExperience.dao.findFirst(sqlbb,getCUserOrganIds());
						ProductOrgExperience kb = ProductOrgExperience.dao.findFirst(sqlkb,getCUserOrganIds());
						ProductOrgExperience fr = ProductOrgExperience.dao.findFirst(sqlfr,getCUserOrganIds());
						if(serviceShaping!=null){
							if(serviceShaping.getFloat(ServiceShaping.column_ybjyusage)!=null){
								 ybjy = serviceShaping.getFloat(ServiceShaping.column_ybjyusage);
								 BigDecimal bd = new BigDecimal(sumjy+ybjy); 
								 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
								// sumjy = sumjy +ybjy;
							}
							if(serviceShaping.getFloat(ServiceShaping.column_gbjyusage)!=null){
								 gbjy = serviceShaping.getFloat(ServiceShaping.column_gbjyusage);
								 BigDecimal bd = new BigDecimal(sumjy+gbjy); 
								 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
								// sumjy = sumjy +gbjy;
							}
							if(serviceShaping.getFloat(ServiceShaping.column_dtjyusage)!=null){
								 dtjy = serviceShaping.getFloat(ServiceShaping.column_dtjyusage);
								 BigDecimal bd = new BigDecimal(sumjy+dtjy); 
								 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
								// sumjy = sumjy +dtjy;
							}
							if( serviceShaping.getFloat(ServiceShaping.column_xtjyusage)!=null){
								 xtjy = serviceShaping.getFloat(ServiceShaping.column_xtjyusage);
								 BigDecimal bd = new BigDecimal(sumjy+xtjy); 
								 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
								// sumjy = sumjy +xtjy;
							}
							
							if(bb!=null){
								if(serviceShaping.getFloat(ServiceShaping.column_bbjyusage)!=null){
									 bbjy = serviceShaping.getFloat(ServiceShaping.column_bbjyusage);
									 BigDecimal bd = new BigDecimal(sumjy+bbjy); 
									 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
									// sumjy = sumjy +bbjy;
								}
							}
							if(kb!=null){
								if(serviceShaping.getFloat(ServiceShaping.column_kbjyusage)!=null){
									 kbjy = serviceShaping.getFloat(ServiceShaping.column_kbjyusage);
									 BigDecimal bd = new BigDecimal(sumjy+kbjy); 
									 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
									// sumjy = sumjy +kbjy;
								}
							}
							if(fr!=null){
								if(serviceShaping.getFloat(ServiceShaping.column_zfrjyusage)!=null){
									 zfrjy = serviceShaping.getFloat(ServiceShaping.column_zfrjyusage);
									 BigDecimal bd = new BigDecimal(sumjy+zfrjy); 
									 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
									// sumjy = sumjy +zfrjy;
								}
								if( serviceShaping.getFloat(ServiceShaping.column_yfrjyusage)!=null){
									 yfrjy = serviceShaping.getFloat(ServiceShaping.column_yfrjyusage);
									 BigDecimal bd = new BigDecimal(sumjy+yfrjy); 
									 sumjy= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();   
									// sumjy = sumjy +yfrjy;
								}
							}
							
							
							
							
							if(serviceShaping.getFloat(ServiceShaping.column_ybgusage)!=null){
								 ybg = serviceShaping.getFloat(ServiceShaping.column_ybgusage);
								 BigDecimal bd = new BigDecimal(sumg+ybg); 
								 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
								 //sumg = sumg+ybg;
							}
							if(serviceShaping.getFloat(ServiceShaping.column_gbgusage)!=null){
								 gbg = serviceShaping.getFloat(ServiceShaping.column_gbgusage);
								 BigDecimal bd = new BigDecimal(sumg+gbg); 
								 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
								// sumg = sumg+gbg;
							}
							if(serviceShaping.getFloat(ServiceShaping.column_dtgusage)!=null){
								 tdg = serviceShaping.getFloat(ServiceShaping.column_dtgusage);
								 BigDecimal bd = new BigDecimal(sumg+tdg); 
								 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
								// sumg = sumg+tdg;
							}
							if(serviceShaping.getFloat(ServiceShaping.column_xtgusage)!=null){
								 xyg = serviceShaping.getFloat(ServiceShaping.column_xtgusage);
								 BigDecimal bd = new BigDecimal(sumg+xyg); 
								 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
								// sumg = sumg+xyg;
							}
							
							if(bb!=null){
							if(serviceShaping.getFloat(ServiceShaping.column_bbgusage)!=null){
								 bbg = serviceShaping.getFloat(ServiceShaping.column_bbgusage);
								 BigDecimal bd = new BigDecimal(sumg+bbg); 
								 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
								// sumg = sumg+bbg;
							}
							}
							if(kb!=null){
								if(serviceShaping.getFloat(ServiceShaping.column_kbgusage)!=null){
									 kbg = serviceShaping.getFloat(ServiceShaping.column_kbgusage);
									 BigDecimal bd = new BigDecimal(sumg+kbg); 
									 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
									 //sumg = sumg+kbg;
								}
							}
							if(fr!=null){
								if(serviceShaping.getFloat(ServiceShaping.column_zfrgusage)!=null){
									 zfrg = serviceShaping.getFloat(ServiceShaping.column_zfrgusage);
									 BigDecimal bd = new BigDecimal(sumg+zfrg); 
									 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
									// sumg = sumg+zfrg;
								}
								if( serviceShaping.getFloat(ServiceShaping.column_yfrgusage)!=null){
									 yfrg = serviceShaping.getFloat(ServiceShaping.column_yfrgusage);
									 BigDecimal bd = new BigDecimal(sumg+yfrg); 
									 sumg= bd.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue(); 
									 //sumg = sumg+yfrg;
								}
								
							}
							
						}
						
						/*for(Code part : parts){
							String sql_part = getSqlMy(CustomerInfoStatisitSQL.sqlId_partProductUse);
							Record part_sy = Db.findFirst(sql_part, customerIds, part.getPKValue(), product.getPKValue(), day);
							if(null != part_sy){
								r.set(product.getStr("bh") + "_" + part.getStr(Code.column_code), part_sy.getDouble("us"));
								sy_sum += part_sy.getDouble("us");
							}
						}*/
						
						r.set("ybjy", ybjy);
						r.set("dtjy", dtjy);
						r.set("gbjy", gbjy);
						r.set("xtjy", xtjy);
						r.set("bbjy", bbjy);
						r.set("kbjy", kbjy);
						r.set("zfrjy", zfrjy);
						r.set("yfrjy", yfrjy);
						r.set("ybg", ybg);
						r.set("dtg", tdg);
						r.set("gbg", gbg);
						r.set("xtg",xyg);
						
						r.set("bbg", bbg);
						r.set("kbg", kbg);
						r.set("zfrg", zfrg);
						r.set("yfrg",yfrg);
						r.set("sumjy", sumjy);
						r.set("sumg",sumg);
						
				
					}
					
					//if(products.size() > 0){
					//	for(Product product : products){
							
							//精油产品购买
							String sql_product = getSqlMy(CustomerInfoStatisitSQL.sqlId_productSales);
							Record jygm_sum = Db.findFirst(sql_product, customerIds, jyproduct.getPKValue(), day);
							if(null != jygm_sum){
								Double exper = Double.parseDouble(jyproduct.getStr(Product.column_proExperience));
								r.set( "jygm", jygm_sum.getBigDecimal("num").multiply(BigDecimal.valueOf(exper)));
								
							}
							
							//膏产品购买
							
							Record ggm_sum = Db.findFirst(sql_product, customerIds, gproduct.getPKValue(), day);
							if(null != ggm_sum){
								Double exper = Double.parseDouble(gproduct.getStr(Product.column_proExperience));
								r.set( "ggm", ggm_sum.getBigDecimal("num").multiply(BigDecimal.valueOf(exper)));
								
							}
							
						if(i==days.size()){
							//产品结余
							String sql_surplus = getSqlMy(CustomerInfoStatisitSQL.sqlId_productSurplus);
							Record jy_sum = Db.findFirst(sql_surplus, customerIds, jyproduct.getPKValue());
							if(null != jy_sum){
								r.set("jyjy", jy_sum.getFloat("totalExperience"));
								
							}
							
							//产品结余
							Record gjy_sum = Db.findFirst(sql_surplus, customerIds, gproduct.getPKValue());
							if(null != gjy_sum){
								r.set("gjy", gjy_sum.getFloat("totalExperience"));
								
							}
						}
							
						
						
								
							//}
							
						//}
					if(r.toString().length() > 2 ){
						r.set("date", day);
						result.add(r);
					}
				}
			}
		}
		renderJson(result);
	}
	/**跳转至月度每日关键指标
	 * 
	 */
	public  void  toCustomerMonthEverydayKeyIndex()
	{
		setAttr("customerIds", getPara("customerIds"));
		Customer  cus=Customer.dao.findById(getPara("customerIds"));
		SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM"); 
		setAttr("startTime", sim.format(cus.getDate(Customer.column_registtime)));
		render("/customer/customerMonthEverydayKeyIndex.html");
	}
	/**获取顾客月度每日关键指标
	 * @throws ParseException 
	 * 
	 */
	public  void  LookCustomerMonthEverydayKeyIndex() throws ParseException
	{	
		String customerIds = getPara("customerIds","-1");
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		List<Record> recordList=customerInfoStatisticService.LookCustomerMonthEverydayKeyIndex(getCUserOrganIds(),customerIds,startTime,endTime);
		renderJson(recordList);
	}
}
